<template>
    <el-main v-loading="loading">
        <div class="margin_bottom_30">
            <el-button
                :type="activeIndex === index ? 'primary' : 'default'"
                size="small"
                @click="handleActive(item, index)"
                v-for="(item, index) of goodsStateList"
                :key="index">
                {{item.name}}({{item.count}})
            </el-button>
        </div>
        <el-row :gutter="20" class="margin_bottom_30" type="flex">
            <el-col :span="4">
                <el-input placeholder="商品名称" size="small" v-model="filterData.productName"></el-input>
            </el-col>
            <el-col :span="4">
                <el-select
                    v-model="filterData.categoryUid"
                    prop="campaignState"
                    placeholder="请选择商品分类"
                    size="small"
                    style="width:100%"
                    @change="checkCategory">
                    <el-option
                        v-for="item in categoryDataList"
                        :key="item.labelId"
                        :label="item.labelText"
                        :value="item.labelId"></el-option>
                </el-select>
            </el-col>
            <!-- <el-col :span="3">
                <el-select
                    class="searchStyle_action"
                    v-model="filterData.brandUid"
                    prop="campaignState"
                    placeholder="请选择品牌"
                    size="small"
                    @change="checkBrand">
                    <el-option
                        v-for="item in BrandList"
                        :key="item.type"
                        :label="item.name"
                        :value="item.type"></el-option>
                </el-select>
            </el-col> -->
            <el-col :span="4" :offset="1">
                <p style="display: flex">
                    <el-button type="primary" size="small" @click="search">搜 索</el-button>
                    <el-button size="small" @click="resetQuery">重 置</el-button>
                    <el-button type="primary" size="small" @click="handleActionPage">新增商品</el-button>
                </p>
            </el-col>
        </el-row>

        <el-table
            :data="goodsList"
            border
            :row-key="row => row.productUid"
            height="580"
            :header-cell-style="{background:'#afafaf',color:'#606266'}"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
        >
            <el-table-column align="center" type="selection" reserve-selection width="40"></el-table-column>
            <el-table-column prop="sourceInfo" width="250" label="商品名称">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.productName">
                       <p>{{scope.row.productName | controlLength}}</p>
                    </el-tooltip>
                    <!-- <p>品牌：{{scope.row.salePrice}}</p> -->
                    <!-- <p>{{scope.row.originPrice}}</p> -->
                    <el-button type="text" @click="handleTags(scope.row)" size="small" disabled>打标签</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="listImageUrl" align="center" width="150" label="商品图片">
                <template slot-scope="scope">
				    <img v-image-preview :src="scope.row.listImageUrl" width="60" />
			    </template>
            </el-table-column>
            <el-table-column width="200" label="进价/心意价/原价">
                <template slot-scope="scope">
                    <p>进价：<span class="text-price">{{$util.prices(scope.row.minPrice)}}</span></p>
                    <p style="text-align: right;">心意价：<span class="text-price">{{$util.prices(scope.row.salePrice)}}</span></p>
                    <p>原价：<span class="text-price">{{$util.prices(scope.row.originPrice)}}</span></p>
                </template>
            </el-table-column>
            <el-table-column prop="saleCount" align="center" width="200" label="销量"></el-table-column>
            <el-table-column prop="usableStock" align="center" width="200" label="库存"></el-table-column>
            <el-table-column prop="status" align="center" width="100" label="状态">
                <template slot-scope="scope">
                    <span style="font-size: 14px">{{getGoodsStatus(scope.row.status)}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="sourceInfo" align="center"  label="操作" width="200">
                <template slot-scope="scope">
                    <el-button type="text" @click="handlePreView(scope.row)" size="small">查看</el-button>
                    <el-button v-if="!scope.row.status" type="text" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                    <el-button type="text" v-if="!scope.row.status" @click="handleDel(scope.row)" size="small">删除</el-button>
                    <template v-if="scope.row.status === 1">
                        <el-button type="text" @click="handleUpdate(scope.row)" size="small">下架</el-button>
                    </template>
                    <template v-else>
                        <el-button type="text" @click="handleUpdate(scope.row)" size="small">上架</el-button>
                    </template>
                </template>
            </el-table-column>
        </el-table>

        <el-row class="footer">
            <el-col :span="12">
				<el-checkbox
                    v-model="checkAll"
                    :disabled="!goodsList.length"
                    @change="handleCheckAllChange">全选
                </el-checkbox>
			</el-col>
			<el-col :span="12">
                 <el-pagination
                    @current-change="handleCurrentChange"
                    :current-page="page"
                    :page-size="10"
                    background
                    class="text_align_right"
                    :disabled="!goodsList.length"
                    :total="count"
                    layout="total, prev, pager, next, jumper">
                </el-pagination>
			</el-col>
		</el-row>
     
		<el-drawer
			size="50%"
			destroy-on-close
            @close="handleClose"
			:visible.sync="openPreviewPage">
				<goods-preview ref="preview" :transData="goodsInfo" @ClosePreviewPage="handleClose"></goods-preview>
		</el-drawer>
      
		<el-dialog
            :title="!goodsInfo.productUid ? '添加商品' : '编辑商品'"
            @close="handleCloseAction"
            :visible.sync="showActionPage"
            destroy-on-close
            :modal-append-to-body="false"
            :close-on-click-modal="false"
            width="40%">
			<goods-action
                ref="templateRef"
                :infoData="goodsInfo"
                :storeList="storeList"
                @func="closeTemplatePage"
                :categoryDataList="categoryDataList"></goods-action>
		</el-dialog>
    </el-main>
</template>
<script>
    import goodsAction from './goods/action.vue';
    import goodsPreview from './goods/preview.vue';
    import {
        getGoodslist,
        deleteGoods,
        categoryList,
        merchantList,
        updateGoodsState
    } from "@/api/table";
    import utils from '@/utils/utils';

    export default {
        name: "GOODS_LIST",
        filters: {
            controlLength: curStr => utils.controlLength(curStr, 15),
        },
        data() {
            return {
                activeIndex: 0,
                goodsStateList: [{
                    name: '全部商品',
                    count: 0,
                    status: ''
                }, {
                    name: '已上架',
                    count: 0,
                    status: 1
                }, {
                    name: '未上架',
                    count: 0,
                    status: 2
                }, {
                    name: '草稿',
                    count: 0,
                    status: 0
                }],
                count: 0,
                checkAll: false, // 全选
                openPreviewPage: false, // 预览
                // BrandList: [], // 品牌
                categoryDataList: [], // 商品分类
                goodsList: [],
                storeList: [], // 商户
                loading: false,
                page: 1,
                showActionPage: false,
                goodsInfo: {},
                filterData: {
                    categoryUid: '',
                    labelId: '',
                    productName: '',
                    status: ''
                },
            }
        },
        components: {
            goodsAction,
            goodsPreview
        },
        mounted() {
            this.getData();
            this.getCategoryList();
            this.getMerchantList();

            // 监听预览msg
            this.$event.on('ShowGoodsPreviewPage', info => {
                this.handlePreView(info)
            });
        },
        beforeDestroy() {
            this.$event.off('ShowGoodsPreviewPage');
        },
        methods: {
            // 商户列表
            getMerchantList() {
                merchantList().then(res => {
                    if (res.data.isSuccessful === "Y") {
                        this.storeList = res.data.data
                    }
                }).catch()
            },
            // 分类
            getCategoryList() {
                categoryList({
                    labelBusinessType: 4
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        this.categoryDataList = res.data.data
                    }
                }).catch()
            },
            // 顶部
            handleActive(data, index) {
                if (this.activeIndex === index) return
                this.activeIndex = index;
                this.filterData.status = data.status;
                this.getData()
            },
            // 获取商品状态
            getGoodsStatus(status) {
                const info = this.goodsStateList.find(item => item.status === status) || {}
                return !Object.keys(info).length ? '' : info.name
            },
            // 搜索
            search(){
                this.getData();
            },
            // 加载第几页
            handleCurrentChange(val) {
                this.page = val;
                //修改页数，重新加载
                this.getData();
            },
            // 全选
            handleCheckAllChange(val) {
                if (this.checkAll) {
                    this.$refs.multipleTable.toggleAllSelection();
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            // 重置
            resetQuery() {
                this.activeIndex = 0;
                this.filterData = {};
                this.page = 1;
                this.getData();
            },
            // 预览
            handlePreView(info = {}) {
                this.goodsInfo = info;
                this.openPreviewPage = true;
                // 同步数据
				this.$nextTick(() => {
					this.$refs.preview.updateData()
				})
			},
			handleClose() {
                this.openPreviewPage = false;
                this.handleCloseAction()
            },

            handleCloseAction() {
                this.goodsInfo = {}
            },
            // 商品分类
            checkCategory(e) {
                this.filterData.categoryUid = e;
                this.getData()
            },
            // 选择品牌
            checkBrand(e) {
                this.filterData.brandUid = e
            },
            handleActionPage() {
                this.showActionPage = true
            },
            closeTemplatePage(data) {
                this.handleCloseAction()
                this.showActionPage = data.action;
                data.refresh && this.getData();
            },
            // 监听选择的内容
            handleSelectionChange(val) {
                // console.log(val)
                this.checkAll = this.goodsList.length === val.length
            },
            // 打标签
            handleTags(info) {

            },
            // 获取数据
            getData() {
                this.loading = true
                getGoodslist({
                    ...this.filterData,
                    page: this.page - 1
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        const {
                            count,
                            productList,
                            onlineProduct,
                            draftProduct,
                            allProduct,
                            notOnProduct 
                        } = res.data.data;
                        this.count = count;
                        this.goodsStateList = [{
                            name: '全部商品',
                            count: allProduct,
                            status: ''
                        }, {
                            name: '已上架',
                            count: onlineProduct,
                            status: 1
                        }, {
                            name: '已下架',
                            count: notOnProduct,
                            status: 2
                        }, {
                            name: '草稿',
                            status: 0,
                            count: draftProduct
                        }];

                        this.goodsList  = productList;
                    }
                }).catch(err => {

                }).finally(() => {
                    if (this.loading) {
                        this.loading = false
                    }
                });
            },
            // 编辑
            handleEdit(info) {
                this.goodsInfo = info;
                this.handleActionPage();
                // 同步数据
				this.$nextTick(() => {
					this.$refs.templateRef.updateData()
				})
            },
            // 更改商品状态
            handleUpdate(info) {
                this.$confirm( `是否${info.status !== 1 ? '上架' : '下架'}该商品?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                     let status = info.status !== 1 ? 1 : 2;
					updateGoodsState({
                        productUid: info.productUid,
                        status
                    }).then(res => {
                        if(res.data.isSuccessful !== "Y"){
                            this.$message.error(res.data.message);
                            return
                        }

                        this.$message.success(res.data.message);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch();
            },
            // 删除
            handleDel(info) {
                this.$confirm("是否删除该商品?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
					deleteGoods({
                        productUid : info.productUid,
                    }).then(result => {
                        if(result.data.isSuccessful !== "Y"){
                            this.$message.error(result.data.message);
                            return
                        }

                        this.$message.success(result.data.message);
                        this.goodsList = this.goodsList.filter(item => item.productUid !== info.productUid);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch(() => {
					this.$message({
						type: "info",
						message: "已取消移除"
					});
				});
            },
        }
    }
</script>
<style lang="scss" scoped>
    
</style>
